var searchData = {};
//商品列表品类选择事件
function checkBtn(n) {
        $('#myCheckboxArea').find('.hidDiv').hide();
        $('#myCheckboxArea').find('.hidDiv').eq(n).show();
        $('#myCheckboxArea').find('.button_san').show();
        $('#myCheckboxArea').find('.top_san').hide();
        $('#myCheckboxArea').find('.button_san').eq(n).hide();
        $('#myCheckboxArea').find('.top_san').eq(n).show();
        $('#myCheckboxArea').find('.action').hide();
        $('#myCheckboxArea').find('.action').eq(n).show();
}
//品类选择div确定事件
function determine(n) {
        $('#myCheckboxArea').find('.hidDiv').eq(n).hide();
        $('#myCheckboxArea').find('.action').eq(n).hide();
        $('#myCheckboxArea').find('.button_san').eq(n).show();
        $('#myCheckboxArea').find('.top_san').eq(n).hide();
}
//新增商品类别按钮选择事件
function myAddCheck(n) {
    $('.select_a_onclick').next('div').hide();
    $('.select_a_onclick').next('div').eq(n).show();
    $('.select_a_div').hide();
    $('.select_a_div').eq(n).show();
}
//新增商品类别确定按钮
function myDetermine(n) {
    $('.select_a_onclick').next('div').eq(n).hide();
    $('.select_a_div').eq(n).hide();
}
$( function () {

    //新增优惠筛选满减满送按钮事件
    $( ".reduce_give" ).click( function (e) {
        e.preventDefault()
        $(this).tab('show');
        var title = $(this).html();
        if (title.indexOf("满减") >= 0) {

        } else if (title.indexOf("满送") >= 0) {

        }

        $( ".reduce_give" ).removeClass( "active_a" );
        $( this ).addClass( "active_a" );
        var value = $( this ).attr( "data_value" );

        var title = [];
        title[0] = {navTitle: "商品管理", e_navTitle: "Commodity management", titleImg: 1};
        title[1] = {navTitle: "新增优惠", e_navTitle: "New offers", titleImg: 1};
        if ( value == "减" ) {

            $(".activity_name").html('<span>满减活动名称</br><span class="color-6">Reduce the activity name</span></span>') ;
            $(".placeholder_name").html('<span>请输入满减活动名称<br/><span>Please enter the name</span></span>') ;

            $("#full-reduce").css("display","block");
            $("#full-give").css("display","none");

            title[2] = {navTitle: "满减", e_navTitle: "Full reduction", titleImg: 0};
        } else {
            $(".activity_name").html('<span>满送活动名称</br><span class="color-6">Reduce the activity name</span></span>') ;
            $(".placeholder_name").html('<span>请输入满送活动名称<br/><span>Please enter the name</span></span>') ;

            $("#full-reduce").css("display","none");
            $("#full-give").css("display","block");

            title[2] = {navTitle: "满送", e_navTitle: "Full delivery", titleImg: 0};
        }
        vm.saveData.discount.name = "" ;
        vm.saveData.discount.condition_money ="" ;
        window.parent.editTitle(title);
    } );
    $( ".show-modal" ).focus( function () {
        $( '#myTypeModal' ).modal( {
            keyboard : true
        } )
    } );
} );
vm = new Vue( {
    el : "#myTabContent" ,
    data : {
        //商品列表数据
        supplyList : {
            rows : [] ,
            total : 0 ,
            page : 1 ,
            pageSize : 10 ,
        } ,
        //优惠管理列表数据
        discountList : {
            rows : [] ,
            total : 0 ,
            page : 1 ,
            pageSize : 1
        } ,
        // 分类、品牌数据
        category : {
            category : [] ,
            type : [] ,
            small_type : [] ,
            brand : [] ,
        } ,

        new_category : {
            category : [] ,
            type : [] ,
            small_type : [] ,
            brand : [] ,
        } ,
        addProductType:{
            category_ids : [] ,
            type_ids : [] ,
            small_type_ids : [] ,
            brand_ids : []
        },
        // 搜索数据
        searchData : {
            name : '' ,
            category : {
                category_ids : [] ,
                type_ids : [] ,
                small_type_ids : [] ,
                brand_ids : [] ,
            } ,
            price : {
                up : '' ,
                down : '' ,
            } ,
            stock : {
                up : '' ,
                down : '' ,
            } ,
            is_shelves : '0' ,
            discount_type : '' ,
            discount_status : '' ,
            discount_name : '' ,
            pageNumber : '' ,
            pageSize : '' ,
        } ,
        // 新增表单数据
        saveData : {
            // 新增商品
            product : {
                name : '' ,
                description : '' ,
                origin : '' ,
                image : '' ,
                img : [] ,
                imgs : [] ,
                price : '' ,
                unit:'',
                number:'',
                stock : '' ,
                is_include_tax : 1,
                is_shelves : 3 ,
                specification : [] ,
                supplier_id:''
            } ,
            // 新增优惠
            discount : {
                type : '',
                name : '',
                supplier_id : '',
                end_time : '',
                start_time : '',
                condition_num : '',
                relief_money : '',
                id : '',                    //参与活动商品id
                product_name : '',          //参与活动商品名称
                product_price:'',           //参与活动商品单价
                give:''
            }
        } ,
        // 添加规格数据
        Speci : {
            speci : {
                number: '',
                speci : '' ,
                price : '' ,
            } ,
            edit : {
                number: '',
                speci : '' ,
                price : '' ,
            } ,
            specification : [] ,
        } ,
        productInfo:{
            id:'',
            stock:'',
            price:'',
            unit:''
        },
        num:0,
        supplier_id:'',
        giftGoods:'',
        loading: true
    } ,
    methods : {
        // 商品/优惠搜索
        searchs : function ( index ) {
            searchData = this.searchData;
            if(searchCheck(searchData) == false){
                return;
            };
            this.loading = true;
            if ( index == 1 ) {
                this.supplyListInit( 0 , 1 , 10 );
            } else {
                this.discountListInit( 0 , 1 , 10 );
            }
        } ,
        // 初始化商品管理
        supplyListInit : function ( type , pageNumber , pageSize ) {
            delChecked( "product" );
            if ( type == 1 ) {
                pageNumber = parseInt( pageNumber ) - 1;
            } else if ( type == 2 ) {
                pageNumber = parseInt( pageNumber ) + 1;
            }
            if ( pageNumber < 1 ) {return;}
            var totalPage;
            if ( this.supplyList.total != 0 ) {
                totalPage = this.supplyList.total % pageSize == 0 ? this.supplyList.total / pageSize : (this.supplyList.total / pageSize) + 1;
            }
            if ( pageNumber > totalPage ) {return;}
            var data = {
                search : searchData ,
                pageSize : pageSize ,
                pageNumber : pageNumber,
                supplier_id:localStorage.getItem("suppliesId")
            };
            $.ajax( {
                url : "/apishop/Product/getProducApi" ,
                dataType : 'json' ,
                type : 'POST' ,
                data : data ,
                success : function ( res ) {
                    vm.supplier_id = localStorage.getItem("suppliesId");
                    vm.supplyList.total = res.count;
                    vm.supplyList.rows = res.data;
                    vm.supplyList.page = res.pageNumber;
                    vm.loading = false;
                    //console.log(vm.supplyList.rows);
                } ,
                error : function () {
                    vm.loading = false;
                    layer.msg( '网络错误！',{
                        skin:'winning-class',//自定义样式winning-class
                        time:3000
                    } );
                }
            } )
        } ,
        //初始化优惠管理页面
        discountListInit : function ( type , pageNumber , pageSize ) {
            delChecked( "discounts" );
            if ( type == 1 ) {
                pageNumber = parseInt( pageNumber ) - 1;
            } else if ( type == 2 ) {
                pageNumber = parseInt( pageNumber ) + 1;
            }
            if ( pageNumber < 1 ) {return;}
            var totalPage;
            if ( this.discountList.total != 0 ) {
                totalPage = this.discountList.total % pageSize == 0 ? this.discountList.total / pageSize : (this.discountList.total / pageSize) + 1;
            }
            if ( pageNumber > totalPage ) {return;}
            var data = {
                search : searchData ,
                pageSize : pageSize ,
                pageNumber : pageNumber,
                supplier_id:localStorage.getItem("suppliesId")
            };
            $.ajax( {
                url : "/apishop/Product/getDiscountList" ,
                dataType : 'json' ,
                type : 'POST' ,
                data : data ,
                success : function ( res ) {
                    vm.discountList.total = res.count;
                    vm.discountList.rows = res.data;
                    vm.discountList.page = res.pageNumber;
                    vm.loading = false;
                } ,
                error : function () {
                    vm.loading = false;
                    layer.msg( '网络错误！',{
                        skin:'winning-class',//自定义样式winning-class
                        time:3000
                    } );
                }
            } )
        } ,
        // 重置搜索表单
        restForm : function () {
            restForms( this.searchData );
            this.searchData.is_shelves = '0';
            restButtonCss();
        },
          //添加选中效果
        setCheckboxSelect: function (event) {
            var status = $(event.currentTarget).prev().prop("checked");
            if (status) {
                $(event.currentTarget).removeClass("active-bg-color");
            } else {
                $(event.currentTarget).addClass("active-bg-color");
            }
        },
        // 分类初始化接口
        getType : function ( first , second ,type) {
           var searchType_one ;
            switch (type){
                case 'search': //商品列表的 分类 联动
                    searchType_one = this.searchData.category[ first ] ;
                    //console.log(searchType_one);
                    break ;
                case  'newProduct':
                    searchType_one = this.addProductType[ first ] ;
                    break ;
                default:
                    break ;
            }
            if ( first ) {
                if ( $.isEmptyObject( searchType_one ) ) {
                   if('search' == type){
                       this.category[ second ] = [];
                   }else{
                       this.new_category[ second ] = [];
                   }
                    return;
                }
            }
            var _this = this , data = { parent_id : searchType_one };
            axios.post( '/apishop/Product/getThreeType' , data , {
                emulateJSON : true
            } ).then( function ( res ) {
                if('search' == type){
                    _this.category[ second ] = res.data;
                }else{
                    _this.new_category[ second ] = res.data;
                }
            } , function ( res ) {
                layer.msg( '网络错误！',{
                    skin:'winning-class',//自定义样式winning-class
                    time:3000
                } );
            } );
        } ,
        // 品牌初始化接口
        getBrand : function (dom,str) {
            var pid = boxCombStr('#'+dom);
            var _this = this;
            axios.post( '/apishop/Product/getThreeBrand' ,{pid:pid},{
                emulateJSON : true
            } ).then( function ( res ) {
                if('search'==str){
                    _this.category.brand = res.data;
                }else{
                    _this.new_category.brand = res.data;
                }

            } , function ( res ) {
                layer.msg( '网络错误！',{
                    skin:'winning-class',//自定义样式winning-class
                    time:3000
                } );
            } );
        } ,
        // 搜索单选数据
        setStatus : function ( index , id ) {
            this.searchData[ index ] = id;
            //this.supplyListInit();
        } ,
        limit:function (file) {
            var reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = function(theFile) {
                var image = new Image();
                image.src = theFile.target.result;
                image.onload = function() {
                    if(image.width != image.height){
                        // layer.msg('上传图片必须为正方形');
                    }
                };
            };
        },
        // 上传图片
        uploadImg : function ( e ) {
            this.loading = true;
            var f = e.target.files[0];
            var data = new FormData() , _this = this , html = '' , url = '/apishop/Product/uploadImg' , name , ext;
            $.each( e.target.files , function ( i , v ) {
                data.append( e.target.id + '[]' , v );
            } );
            data.append( 'dir' , 'product' );
            data.append( 'name' , e.target.id );
            axios.post( url , data , {
                emulateJSON : true
            } ).then( function ( res ) {
                if ( res.data.status == 200 ) {
                    $.each( res.data[ e.target.id ] , function ( i , v ) {
                        _this.saveData.product[ e.target.id ].push( v );
                    } );
                    $.each( _this.saveData.product[ e.target.id ] , function ( i , v ) {
                        name = v.split( '/' )[ 1 ].split( '.' )[ 0 ];
                        ext = v.split( '/' )[ 1 ].split( '.' )[ 1 ];
                        html += "<div style=\"position: relative;\" class='form-group' id='" + name + "' >";
                        html += "<img src='"+oss_url + v + "' />";
                        html += "<div  class='img_remove_a' onclick='removeNodes(\"" + name + "\",\"" + ext + "\",\"" + e.target.id + "\")'></div>";
                        html += "</div>";
                    } );
                    $( '.' + e.target.id ).html( html );
                }else if (res.data.status == 209) {
                    layer.msg('请上传正方形的图片</br>please upload a square picture',{
                        skin:'winning-class',//自定义样式winning-class
                        time:3000
                    })
                }else {
                    layer.msg('上传失败</br>upload failure',{
                        skin:'winning-class',//自定义样式winning-class
                        time:3000
                    })
                }
                setTimeout(function () {
                    _this.loading = false;
                }, 300);
            } , function ( res ) {

            } );
        } ,
        // 上传图片
        uploadImg1 : function ( e ) {
            this.loading = true;
            var f = e.target.files[0];
            var data = new FormData() , _this = this , html = '' , url = '/apishop/Product/uploadImg1' , name , ext;
            $.each( e.target.files , function ( i , v ) {
                data.append( e.target.id + '[]' , v );
            } );
            data.append( 'dir' , 'product' );
            data.append( 'name' , e.target.id );
            axios.post( url , data , {
                emulateJSON : true
            } ).then( function ( res ) {
                if ( res.data.status == 200 ) {
                    $.each( res.data[ e.target.id ] , function ( i , v ) {
                        _this.saveData.product.imgs.push( v );
                    } );
                    $.each( _this.saveData.product.imgs , function ( i , v ) {
                        name = v.split( '/' )[ 1 ].split( '.' )[ 0 ];
                        ext = v.split( '/' )[ 1 ].split( '.' )[ 1 ];
                        html += "<div style=\"position: relative;\" class='form-group' id='" + name + "' >";
                        html += "<img src='"+oss_url + v + "' />";
                        html += "<div  class='img_remove_a' onclick='removeNodes(\"" + name + "\",\"" + ext + "\",\"" + e.target.id + "\")'></div>";
                        html += "</div>";
                    } );
                    $( '.' + e.target.id ).html( html );
                }else if (res.data.status == 209) {
                    layer.msg('请上传正方形的图片</br>please upload a square picture',{
                        skin:'winning-class',//自定义样式winning-class
                        time:3000
                    })
                }else {
                    layer.msg('上传失败</br>upload failure',{
                        skin:'winning-class',//自定义样式winning-class
                        time:3000
                    })
                }
                setTimeout(function () {
                    _this.loading = false;
                }, 300);
            } , function ( res ) {

            } );
        } ,
        // 新增商品、优惠
        addProduct : function ( index,typed)    {
            // this.loading = true;
            var url;
            if ( index == 'product' ) {
                if(!$("#saveCommodity").Validform()){
                    this.loading = false;
                    return ;
                }
                url = '/apishop/Product/addProduct';
                this.num+=1;
                this.saveData[ index ][ 'category_id' ]     = this.addProductType.category_ids;    //类别
                this.saveData[ index ][ 'type_id' ]         = this.addProductType.type_ids;    //种类
                this.saveData[ index ][ 'small_type_id' ]   = this.addProductType.small_type_ids;    //品类
                this.saveData[ index ][ 'brand_id' ]        = this.addProductType.brand_ids;  // 品牌
                this.saveData.product.supplier_id           = localStorage.getItem("suppliesId");
                this.saveData[ index ][ 'image' ]           = this.saveData.product.img[ 0 ];
                this.saveData[ index ][ 'specification' ]   = this.Speci.specification;
                var res = checkForm( this.saveData[ index ]);
                if ( !res[ 'flag' ] ) {
                    layer.msg( res[ 'msg' ] ,{
                        skin:'winning-class',//自定义样式winning-class
                        time:3000
                    });
                    this.loading = false;
                    return false;
                }
            } else if ( index == 'discount' ) {
                this.num+=1;
                this.saveData.discount.start_time   = $("#startTime").val();
                this.saveData.discount.end_time     = $("#endTime").val();
                this.saveData.discount.type         = typed;
                this.saveData.discount.supplier_id  = localStorage.getItem("suppliesId");
                var res = checkDiscount( this.saveData[ index ],typed);
                if ( !res[ 'flag' ] ) {
                    layer.msg( res[ 'msg' ] ,{
                        skin:'winning-class',//自定义样式winning-class
                        time:3000
                    });
                    this.loading = false;
                    return false;
                }
                url = '/apishop/Product/addDiscount'
            }
            var data = this.saveData[ index ];
            // console.log(JSON.stringify(data)); return false;
            axios.post( url , data , {
                emulateJSON : true
            } ).then( function ( res ) {
                if ( 200 == res.data.status ) {
                    this.loading = false;
                    layer.msg( res.data.msg ,{
                        skin:'winning-class',//自定义样式winning-class
                        time:3000
                    } , function () {
                        this.num = 0;
                        window.location.reload();
                    } );
                }else {
                    this.loading = false;
                    layer.msg(res.data.msg,{
                        skin:'winning-class',//自定义样式winning-class
                        time:3000
                    } );
                }
            } , function ( res ) {
                this.loading = false;
                layer.msg('失败',{
                    skin:'winning-class',//自定义样式winning-class
                    time:3000
                });
            } );
        } ,
        // 新增规格页面
        add : function () {
            $( "#myModal" ).modal( 'show' );
            this.Speci.speci.speci = '';
            this.Speci.speci.price = '';
        } ,
        // 新增规格
        addSpeci : function () {

            if ($('#myModal').Validform()) {
                $( "#myModal" ).modal( 'hide' );
                var arr = {};
                arr[ 'speci' ]  = this.Speci.speci.speci;
                arr[ 'price' ]  = this.Speci.speci.price;
                arr[ 'number' ] = this.Speci.speci.number;
                this.Speci.specification.push( arr );
            }
        } ,
        // 编辑规格页面
        edit : function ( index ) {
            $( "#myModal1" ).modal( 'show' );
            this.Speci.edit.number = this.Speci.specification[ index ].number;
            this.Speci.edit.speci  = this.Speci.specification[ index ].speci;
            this.Speci.edit.price  = this.Speci.specification[ index ].price;
            $( "#edit" ).attr( 'index' , index );
        } ,
        // 编辑规格
        editSpeci : function () {
            if ($('#myModal1').Validform()) {
                $("#myModal1").modal('hide');
                var index = $("#edit").attr('index');
                this.Speci.specification[index].number = this.Speci.edit.number;
                this.Speci.specification[index].speci  = this.Speci.edit.speci;
                this.Speci.specification[index].price  = this.Speci.edit.price;
                var arr = [];
                this.Speci.specification.push(arr);
                this.Speci.specification.pop();
            }
        } ,
        // 删除规格
        delSpeci : function ( index ) {
            this.Speci.specification.splice( index , 1 );
        } ,
        formatDateTime1 : function (startTime,endTime) {
          var   start = formatDate(startTime,"yy/MM/dd HH:mm" ) ;
          var   end = formatDate(endTime,"yy/MM/dd HH:mm" ) ;
           var html ='<div><span>'+start+' </span> <br>' +
               '-<span> '+end+'</span></div> ' ;
            return html ;
        },
        formatDateTime2 : function (time) {
            var   start = formatDate(time,"yy/MM/dd&HH:mm" ) ;
            var html ='<div><span>'+start+' </span> </div> ' ;
            return html ;
        }
        ,
        // 上架、下架商品
        upDownProduct : function ( index , id ) {
            var url , data = { id : id };
            if ( index == 1 ) {
                url = '/apishop/Product/upProduct';
            } else if ( index == 2 ) {
                url = '/apishop/Product/downProduct';
            } else {
                layer.msg( '参数错误！' ,{
                    skin:'winning-class',//自定义样式winning-class
                    time:3000
                });
                return false;
            }
            axios.post( url , data , {
                emulateJSON : true
            } ).then( function ( res ) {
                if ( res.data.status == 200 ) {
                    vm.supplyListInit( 0 , 1 , 10 );
                }
            } , function ( res ) {

            } );
        } ,
        // 上、下架优惠
        upDownDiscount:function (index,id) {
            var url , data = { id : id,supplier_id:this.supplier_id};
            if ( index == 1 ) {
                url = '/apishop/Product/upDiscount';
            } else if ( index == 2 ) {
                url = '/apishop/Product/downDiscount';
            } else {
                layer.msg( '参数错误！',{
                    skin:'winning-class',//自定义样式winning-class
                    time:3000
                } );
                return false;
            }
            axios.post( url , data , {
                emulateJSON : true
            } ).then( function ( res ) {
                if ( res.data.status == 200 ) {
                    vm.discountListInit( 0 , 1 , 10 );
                }else {
                    layer.msg(res.data.msg ,{
                        skin:'winning-class',//自定义样式winning-class
                        time:3000
                    });
                }
                // layer.closeAll();
            } , function ( res ) {

            } );
        },
        lookReson:function (id) {
            var url = '/apishop/Product/loseProduct';
            var data = {
                product_id: id
            };
            axios.post( url , data , {
                emulateJSON : true
            } ).then( function ( res ) {
                // layer.alert( res.data.message)
                layer.confirm(res.data.message,{
                    btn: ['<span class="layer_btn_save">确定(determine)</span>'],
                    move:false
                });
            } , function ( res ) {

            } );
        },
        // 删除商品/优惠
        delProduct : function ( first , index , id , dom ) {
            if (index == 2){
                var flag = 0;
                $( "#" + dom + " input[name='ids']" ).each( function ( i , v ) {
                    if ( $( v ).prop( "checked" ) ) {
                        flag++;
                    }
                } );
                if (flag === 0) {
                    if(first == 1){
                        layer.msg("请选择要删除的商品</br>Please select the product to be deleted",{
                            skin:'winning-class',//自定义样式winning-class
                            time:3000
                        });
                    }else {
                        layer.msg("请选择要删除的活动</br>Please select the activity to be deleted",{
                            skin:'winning-class',//自定义样式winning-class
                            time:3000
                        });
                    }
                    return false;
                }
            }
            var url;
            if ( first == 1 ) {
                url = '/apishop/Product/delProduct';
            } else {
                url = '/apishop/Product/delDiscount';
            }
            layer.confirm( '确定要删除吗？<br>Are you sure you want to delete it?' , {
                btn: ['<span class="layer_btn_save">确定(determine)</span>', '取消(cancel)' ],
                move:false
            } , function () {
                var data = {} , arr = [];
                if ( index == 1 ) {
                    data = { id : id };
                } else {
                    $( "#" + dom + " input[name='ids']" ).each( function ( i , v ) {
                        if ( $( v ).prop( "checked" ) ) {
                            arr.push( $( v ).val() );
                        }
                    } );
                    data = { id : arr };
                }
                axios.post( url , data , {
                    emulateJSON : true
                } ).then( function ( res ) {
                    if ( res.data.status == 200 ) {
                        layer.msg( res.data.msg ,{
                            skin:'winning-class',//自定义样式winning-class
                            time:3000
                        }, function () {
                            // window.location.reload();
                            if ( first == 1 ){
                                vm.supplyListInit( 0 , 1 , 10 );
                            }else {
                                vm.discountListInit( 0 , 1 , 10 );
                            }
                        } );
                    }else {
                        layer.msg(res.data.msg ,{
                            skin:'winning-class',//自定义样式winning-class
                            time:3000
                        });
                    }
                } , function ( res ) {

                } );
            } )
        } ,
        // 修改库存和价格
        changeProduct:function(id,stock,price,unit){
            this.productInfo.id    = id;
            this.productInfo.stock = stock;
            this.productInfo.price = price;
            this.productInfo.unit  = unit;
            $( "#changeModal" ).modal( 'show' );
        },

        updateProduct:function () {
            var patrn = /^[0-9]*[0-9][0-9]*$/;
            if (patrn.exec(this.productInfo.stock) ==  null || this.productInfo.stock == ''){
                layer.msg('库存输入有误，请重新输入/The input of the stock is incorrect. Please reenter it',{
                    skin:'winning-class',//自定义样式winning-class
                    time:3000
                });
                return false;
            }
            if (this.productInfo.price < 0){
                layer.msg('价格输入有误，请重新输入/Price input is wrong, please reenter',{
                    skin:'winning-class',//自定义样式winning-class
                    time:3000
                });
                return false;
            }
            var url = '/apishop/product/updateProduct';
            var data = {
                id:this.productInfo.id,
                stock:this.productInfo.stock,
                price:this.productInfo.price
            };
            axios.post( url , data ,{
                emulateJSON:true
            }).then(function (res) {
                console.log(res);
                if(res.status ==200){
                    layer.msg(res.data.msg,{
                        skin:'winning-class',//自定义样式winning-class
                        time:3000
                    });
                    $( "#changeModal" ).modal( 'hide' );
                    vm.supplyListInit( 0 , 1 , 10 );
                }else{
                    layer.msg(res.data.msg,{
                        skin:'winning-class',//自定义样式winning-class
                        time:3000
                    });
                }
            });
        },
        // 初始化满送商品
        getGiftGoods:function () {
            var url = '/apishop/apishop/getProductGivezTree';
            var data = {
                supplier_id: localStorage.getItem("suppliesId")
            };
            axios.post( url , data , {
                emulateJSON : true
            } ).then( function ( res ) {
                if ( 202 == res.data.status) {
                    vm.giftGoods = 1;
                }else {
                    vm.giftGoods = 0;
                }
            } , function ( res ) {
                layer.msg('失败',{
                    skin:'winning-class',//自定义样式winning-class
                    time:3000
                })
            } );
        }
    } ,
    mounted : function () {
        // 分类初始化
        this.getType( null , 'category','search' );
        this.getType( null , 'category','newProduct' );
        // 品牌初始化
        //this.getBrand();
        // 初始化商品列表
        this.supplyListInit( 0 , 1 , 10 );
        // 初始化优惠列表
        this.discountListInit( 0 , 1 , 10 );
        // 初始化满送商品
        this.getGiftGoods();
    }
} );

//删除图片
function removeNodes( name , ext , id ) {
    layer.load( 0 );
    var path = 'product/' + name + '.' + ext , num = $.inArray( path , vm.saveData.product[ id ] );
    var data = { path : path } , url = '/apishop/Product/delImg';
    $.ajax( {
        url : url ,
        dataType : 'json' ,
        type : 'POST' ,
        data : data ,
        success : function ( res ) {
            if ( res.status == 200 ) {
                vm.saveData.product[ id ].splice( num , 1 );
                $( "#" + name ).remove();
                layer.closeAll();
            }
        } ,
        error : function () {
            layer.msg( '网络错误！',{
                skin:'winning-class',//自定义样式winning-class
                time:3000
            } );
        }
    } );
}
//判断商品管理传过来的条件
function searchCheck(where){
    if(where.price.up != ''&& where.price.down != ''){
        if(!Number(where.price.up) || !Number(where.price.down)){
            layer.msg('请输入数字/please enter a number',{
                skin:'winning-class',//自定义样式winning-class
                time:3000
            });
            return false;
        }else{
            if(parseInt(where.price.up) <= parseInt(where.price.down)){
                layer.msg('价格区间输入有误，请重新输入/The input of the price range is incorrect. Please reenter it',{
                    skin:'winning-class',//自定义样式winning-class
                    time:3000
                });
                return false;
            }
        }
    }
    if(where.stock.up != ''&& where.stock.down != ''){
        if(!Number(where.stock.up) || !Number(where.stock.down)){
            layer.msg('请输入数字/please enter a number',{
                skin:'winning-class',//自定义样式winning-class
                time:3000
            });
            return false;
        }else{
            if(parseInt(where.stock.up) <= parseInt(where.stock.down)){
                layer.msg('库存区间输入有误，请重新输入/The input of the stock interval is incorrect. Please reenter it',{
                    skin:'winning-class',//自定义样式winning-class
                    time:3000
                });
                return false;
            }
        }
    }
}
// 重置搜索表单
function restForms( rest ) {
    $.each( rest , function ( i , v ) {
        if ( Object.prototype.toString.call( v ) === '[object Object]' ) {
            restForms( v );
        }
        if ( Object.prototype.toString.call( v ) === '[object Array]' ) {
            rest[ i ] = [];
        } else if ( Object.prototype.toString.call( v ) === '[object String]' ) {
            rest[ i ] = '';
        }
    } ) ;
     // 进行列表选中清除
    $("#commodity").find("input").each(function () {
        console.log( $(this).next());
        $(this).next().removeClass("active-bg-color");
    });
}

// 重置按钮样式
function restButtonCss() {
    $( ".supply_status" ).each( function () {
        $( this ).removeClass( "active_a_supply" );
    } )
    $( ".full_a_click" ).each( function () {
        $( this ).removeClass( "active_a_full" );
    } )
    $( ".status_a_click" ).each( function () {
        $( this ).removeClass( "active_a_status" );
    } )
}
//检查是否为num
function checkNum(event){
    if(!Number(event.value)){
        layer.msg('请输入数字/please enter a number',{
            skin:'winning-class',//自定义样式winning-class
            time:3000
        });
        event.value = '';
    }
}

// 检查表单
function checkForm( data ) {
    var arr = [];
    if ( !data[ 'name' ] ) {
        arr[ 'msg' ] = "请输入商品名称！";
        arr[ 'flag' ] = false;
        return arr;
    }
    if ( !data[ 'description' ] ) {
        arr[ 'msg' ] = "请输入商品简介！";
        arr[ 'flag' ] = false;
        return arr;
    }
    if ( !data[ 'origin' ] ) {
        arr[ 'msg' ] = "请输入商品产地！";
        arr[ 'flag' ] = false;
        return arr;
    }
    if ( data['category_id'].length <1 ) {
        arr[ 'msg' ] = "请选择商品类别！";
        arr[ 'flag' ] = false;
        return arr;
    }
    if ( data['type_id'].length <1 ) {
        arr[ 'msg' ] = "请选择商品种类！";
        arr[ 'flag' ] = false;
        return arr;
    }
    if ( !data['number'] ) {
        arr[ 'msg' ] = "请输入单位数量！";
        arr[ 'flag' ] = false;
        return arr;
    }
    /*if ( data[ 'img' ].length < 1 ) {
        arr[ 'msg' ] = "至少上传1张图片！";
        arr[ 'flag' ] = false;
        return arr;
    }
    if ( data[ 'img' ].length > 10 || data[ 'imgs' ].length > 10 ) {
        arr[ 'msg' ] = "最多只能添加10张图片！";
        arr[ 'flag' ] = false;
        return arr;
    }*/
    if ( !data[ 'price' ] ) {
        arr[ 'msg' ] = "请输入商品单价！";
        arr[ 'flag' ] = false;
        return arr;
    }
    if ( !data[ 'unit' ] ) {
        arr[ 'msg' ] = "请输入商品单位！";
        arr[ 'flag' ] = false;
        return arr;
    }
    if(data['price'])
    if ( !data[ 'stock' ] ) {
        arr[ 'msg' ] = "请输入商品库存！";
        arr[ 'flag' ] = false;
        return arr;
    }
    arr[ 'flag' ] = true;
    return arr;
}
function checkDiscount(data,num) {
    var arr = [];
    /*if ( !data[ 'name' ] ) {
        if (1 == num){
            arr[ 'msg' ] = "请输入满减活动名称！";
        }else {
            arr[ 'msg' ] = "请输入满送活动名称！";
        }
        arr[ 'flag' ] = false;
        return arr;
    }*/
    if ( !data[ 'start_time' ] ) {
        arr[ 'msg' ] = "请选择活动开始时间！";
        arr[ 'flag' ] = false;
        return arr;
    }
    if ( !data[ 'end_time' ] ) {
        arr[ 'msg' ] = "请选择活动结束时间！";
        arr[ 'flag' ] = false;
        return arr;
    }
    if ( data[ 'end_time' ] < data[ 'start_time' ]) {
        arr[ 'msg' ] = "结束时间比活动开始时间早，请重新选择！";
        arr[ 'flag' ] = false;
        return arr;
    }
    if (1 == num){
        if ( !data[ 'condition_num' ] || !data[ 'relief_money' ]) {
            arr[ 'msg' ] = "请输入满减规则！";
            arr[ 'flag' ] = false;
            return arr;
        }
        var money   = parseFloat(data[ 'condition_num' ]) * parseFloat(data[ 'product_price' ]);
        if (parseFloat(data[ 'relief_money' ]) >= parseFloat(money)){
            arr[ 'msg' ] = "减少金额需小于满送条件！";
            arr[ 'flag' ] = false;
            return arr;
        }
    }else {
        if ( !data[ 'condition_num' ] || !data[ 'id' ]) {
            arr[ 'msg' ] = "请输入满送规则！";
            arr[ 'flag' ] = false;
            return arr;
        }
        /*if ( !data[ 'num' ]) {
            arr[ 'msg' ] = "请输入赠送数量！";
            arr[ 'flag' ] = false;
            return arr;
        }*/
    }
    arr[ 'flag' ] = true;
    return arr;
}

// 全选/清空
var isCheckAll = false;
function swapCheck( id ) {
    if ( isCheckAll ) {
        $( "#" + id + " input[name='ids']" ).each( function () {
            this.checked = false;
        } );
        isCheckAll = false;
    } else {
        $( "#" + id + " input[name='ids']" ).each( function () {
            this.checked = true;
        } );
        isCheckAll = true;
    }
}

// 分页清除选中
function delChecked( id ) {
    $( "#" + id + " input" ).each( function () {
        this.checked = false;
    } );
    isCheckAll = false;
}
